<template>
  <div class="auth-page">
    <div class="page-header">
      <h1 class="title">微信授权登录</h1>
      <p class="subtitle">获取用户详细信息，实现个性化服务</p>
    </div>

    <div class="container">
      <div class="auth-content">
        <!-- 授权状态 -->
        <div v-if="authInfo" class="auth-info">
          <div class="auth-card">
            <div class="auth-header">
              <h2>授权信息</h2>
              <span class="auth-status success">已授权</span>
            </div>
            <div class="auth-details">
              <div class="detail-item">
                <label>访问令牌:</label>
                <span class="token">{{ authInfo.accessToken.substring(0, 20) }}...</span>
              </div>
              <div class="detail-item">
                <label>刷新令牌:</label>
                <span class="token">{{ authInfo.refreshToken.substring(0, 20) }}...</span>
              </div>
              <div class="detail-item">
                <label>过期时间:</label>
                <span>{{ formatExpiresTime(authInfo.expiresIn) }}</span>
              </div>
              <div class="detail-item">
                <label>授权范围:</label>
                <span class="scope">{{ authInfo.scope }}</span>
              </div>
            </div>
            <button @click="revokeAuth" class="btn btn-secondary">撤销授权</button>
          </div>
        </div>

        <!-- 授权表单 -->
        <div v-else class="auth-form">
          <div class="auth-card">
            <div class="auth-icon">
              <div class="wechat-icon">🔑</div>
            </div>
            <h2>微信授权登录</h2>
            <p class="auth-desc">授权获取您的微信信息，为您提供更好的服务</p>
            
            <div class="scope-selection">
              <h3>选择授权范围：</h3>
              <div class="scope-list">
                <label v-for="scope in availableScopes" :key="scope.key" class="scope-item">
                  <input 
                    v-model="selectedScopes" 
                    :value="scope.key" 
                    type="checkbox"
                  />
                  <span class="scope-info">
                    <strong>{{ scope.name }}</strong>
                    <small>{{ scope.description }}</small>
                  </span>
                </label>
              </div>
            </div>

            <button 
              @click="requestAuth" 
              class="btn btn-primary auth-btn"
              :disabled="isLoading || selectedScopes.length === 0"
            >
              <span v-if="isLoading" class="spinner"></span>
              {{ isLoading ? '授权中...' : '开始授权' }}
            </button>

            <div class="auth-tips">
              <h3>授权说明：</h3>
              <ul>
                <li>• 我们只会获取您选择的信息</li>
                <li>• 您可以随时撤销授权</li>
                <li>• 您的信息将被安全保护</li>
                <li>• 授权信息仅用于提供服务</li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 功能演示 -->
        <div class="demo-section">
          <h2>授权功能演示</h2>
          <div class="demo-grid">
            <div class="demo-card">
              <div class="demo-icon">👤</div>
              <h3>用户信息</h3>
              <p>获取用户基本信息，如昵称、头像等</p>
            </div>
            <div class="demo-card">
              <div class="demo-icon">📍</div>
              <h3>位置信息</h3>
              <p>获取用户地理位置，提供本地化服务</p>
            </div>
            <div class="demo-card">
              <div class="demo-icon">📱</div>
              <h3>设备信息</h3>
              <p>获取设备相关信息，优化用户体验</p>
            </div>
            <div class="demo-card">
              <div class="demo-icon">🔔</div>
              <h3>消息推送</h3>
              <p>发送重要通知和消息提醒</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useWeChatStore } from '@/stores/wechat'
import { wechatApi } from '@/api/wechat'
import type { AuthInfo } from '@/types'

const wechatStore = useWeChatStore()

const isLoading = ref(false)
const selectedScopes = ref<string[]>([])

const authInfo = computed(() => wechatStore.authInfo)

const availableScopes = ref([
  {
    key: 'snsapi_base',
    name: '基础信息',
    description: '获取用户基本信息（昵称、头像等）'
  },
  {
    key: 'snsapi_userinfo',
    name: '详细信息',
    description: '获取用户详细资料（性别、地区等）'
  },
  {
    key: 'snsapi_login',
    name: '登录授权',
    description: '用于网页应用微信登录'
  },
  {
    key: 'snsapi_message',
    name: '消息推送',
    description: '发送模板消息和客服消息'
  }
])

const requestAuth = async () => {
  if (selectedScopes.value.length === 0) {
    alert('请选择至少一个授权范围')
    return
  }

  isLoading.value = true
  try {
    // 模拟授权码
    const mockCode = 'mock_auth_code_' + Date.now()
    const response = await wechatApi.authLogin(mockCode)
    
    if (response.code === 200) {
      wechatStore.setAuthInfo(response.data)
      alert('授权成功！')
    } else {
      alert('授权失败: ' + response.message)
    }
  } catch (error) {
    console.error('授权失败:', error)
    // 模拟授权成功
    const mockAuth: AuthInfo = {
      accessToken: 'mock_access_token_' + Date.now(),
      refreshToken: 'mock_refresh_token_' + Date.now(),
      expiresIn: 7200,
      scope: selectedScopes.value.join(',')
    }
    
    wechatStore.setAuthInfo(mockAuth)
    alert('模拟授权成功！')
  } finally {
    isLoading.value = false
  }
}

const revokeAuth = () => {
  wechatStore.setAuthInfo(null)
  selectedScopes.value = []
  alert('已撤销授权')
}

const formatExpiresTime = (expiresIn: number) => {
  const now = new Date()
  const expiresAt = new Date(now.getTime() + expiresIn * 1000)
  return expiresAt.toLocaleString('zh-CN')
}

onMounted(() => {
  // 检查是否已授权
  if (!authInfo.value) {
    // 可以在这里添加自动检查授权状态的逻辑
  }
})
</script>

<style scoped>
.auth-page {
  min-height: 100vh;
  position: relative;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 0 0 30px 30px;
  margin-bottom: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 16px;
}

.subtitle {
  font-size: 1.2rem;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

.auth-content {
  max-width: 800px;
  margin: 0 auto;
}

.auth-info {
  margin-bottom: 40px;
}

.auth-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.auth-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.auth-header h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
}

.auth-status {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 500;
}

.auth-status.success {
  background: #e8f5e8;
  color: #07c160;
}

.auth-details {
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item label {
  font-weight: 500;
  color: #333;
  min-width: 100px;
}

.detail-item span {
  color: #666;
  font-family: monospace;
  font-size: 0.9rem;
}

.token {
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
}

.scope {
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.auth-form {
  margin-bottom: 40px;
}

.auth-icon {
  text-align: center;
  margin-bottom: 20px;
}

.wechat-icon {
  width: 80px;
  height: 80px;
  background: #ff976a;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
  margin: 0 auto;
  box-shadow: 0 8px 20px rgba(255, 151, 106, 0.3);
}

.auth-card h2 {
  font-size: 1.8rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  text-align: center;
}

.auth-desc {
  color: #666;
  margin-bottom: 30px;
  font-size: 1.1rem;
  text-align: center;
}

.scope-selection {
  margin-bottom: 30px;
}

.scope-selection h3 {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.scope-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.scope-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border: 2px solid #e5e5e5;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.scope-item:hover {
  border-color: #667eea;
  background: #f8f9ff;
}

.scope-item input[type="checkbox"] {
  margin-top: 4px;
  width: 18px;
  height: 18px;
  accent-color: #667eea;
}

.scope-info {
  flex: 1;
}

.scope-info strong {
  display: block;
  color: #333;
  margin-bottom: 4px;
}

.scope-info small {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
}

.auth-btn {
  width: 100%;
  max-width: 300px;
  padding: 16px;
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 auto 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.auth-tips {
  text-align: left;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.auth-tips h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.auth-tips ul {
  list-style: none;
  padding: 0;
}

.auth-tips li {
  color: #666;
  margin-bottom: 8px;
  font-size: 0.95rem;
}

.demo-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.demo-section h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  text-align: center;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.demo-card {
  text-align: center;
  padding: 20px;
  border-radius: 12px;
  background: #f8f9fa;
  transition: transform 0.3s ease;
}

.demo-card:hover {
  transform: translateY(-4px);
}

.demo-icon {
  font-size: 2rem;
  margin-bottom: 12px;
}

.demo-card h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.demo-card p {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
}

@media (max-width: 768px) {
  .auth-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .title {
    font-size: 2rem;
  }
  
  .subtitle {
    font-size: 1rem;
  }
  
  .demo-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
